import { useState, FC } from "react";
import { Button, Spin, Tag, message } from "antd";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { DndContext, closestCenter } from "@dnd-kit/core";
import { arrayMove, SortableContext } from "@dnd-kit/sortable";
import { httpPost } from "@utils/HttpUtil";
import SelectKnowledgeTree from "src/common/component/SelectKnowledgeTree";

const FunctionSortKnowledge = () => {
  // 状态管理
  const [selectedKey, setSelectedKey] = useState("root");
  const [listData, setListData] = useState([]);
  const [tempOrder, setTempOrder] = useState(["111", "123"]); // 拖拽后的临时顺序
  const [loading, setLoading] = useState(false);

  // 获取节点对应的列表数据
  const fetchListData = () => {
    setLoading(true);
    try {
      const resData = httpPost("/knowledge/getKnowledgeByPid", {
        pid: selectedKey,
      }).data;
      setListData(resData);
      setTempOrder(resData.map((item: any) => item.id)); // 初始化顺序ID数组
    } catch (err) {
      message.error("数据加载失败");
    } finally {
      setLoading(false);
    }
  };

  // 拖拽结束处理
  const handleDragEnd = (event: any) => {
    const { active, over } = event;
    if (active.id !== over.id) {
      setListData((prev) => {
        const oldIndex = prev.findIndex((item: any) => item.id === active.id);
        const newIndex = prev.findIndex((item: any) => item.id === over.id);
        const newData = arrayMove(prev, oldIndex, newIndex);
        var dataList = newData.map((item: any) => item.id);
        setTempOrder(dataList); // 更新顺序ID数组
        return newData;
      });
    }
  };

  // 保存排序结果
  const saveOrder = () => {
    httpPost("/knowledge/sortKnowledge", {
      pid: selectedKey,
      idList: tempOrder,
    });
    message.success("顺序已更新");
  };

  // 可拖拽列表项组件
  const SortableItem: FC<any> = ({ id, name }) => {
    const { attributes, listeners, setNodeRef, transform } = useSortable({
      id,
    });
    const style = { transform: CSS.Transform.toString(transform) };

    return (
      <div
        ref={setNodeRef}
        style={{
          ...style,
          padding: 16,
          borderBottom: "1px solid #eee",
          cursor: "grab",
        }}
        {...attributes}
        {...listeners}
      >
        {name}
      </div>
    );
  };

  return (
    <div style={{ padding: 24 }}>
      {/* 树形选择区域 */}
      <div style={{ marginBottom: 24 }}>
        <SelectKnowledgeTree
          onChange={(value: any) => {
            var key = value[0];
            if (key === undefined || key === null || key === "") {
              key = "root"; // 如果没有选中节点，默认为根节点
            }
            setSelectedKey(key);
          }}
        />
        <Button
          type="primary"
          onClick={fetchListData}
          // disabled={!selectedKey}
          style={{ marginTop: 12 }}
        >
          加载数据
        </Button>
      </div>

      {/* 可拖拽列表区域 */}
      <Spin spinning={loading} style={{ margin: 20 }}>
        <DndContext
          collisionDetection={closestCenter}
          onDragEnd={handleDragEnd}
          
        >
          <SortableContext items={listData.map((item: any) => item.id)} >
          <Tag color={listData.length > 0 ? "green" : "#fff"} style={{
                borderRadius: 8,
                width: "1000px",
                fontSize: 16,
              }}>{listData.map((item: any) => (<SortableItem key={item.id} id={item.id} name={item.name} />))}</Tag>
          </SortableContext>
        </DndContext>

        {listData.length > 0 && (
          <Button type="primary" onClick={saveOrder} style={{ marginTop: 16 }}>
            保存当前顺序
          </Button>
        )}
      </Spin>
    </div>
  );
};

export default FunctionSortKnowledge;
